const connect = require('connect');
const basicAuthConnect = require('basic-auth-connect');

function User() {}

User.users = {
  tobi: 'foo',
  loki: 'bar',
  jane: 'baz'
};

User.authenticate = function (e, callback) {
  const value = User.users[e.user];
  const valid = value == e.pass;
  if (valid) {
    callback(null, e);
  } else {
    callback(new Error('not found'));
  }
};

const app = connect()
  .use(
    basicAuthConnect(function (user, pass, callback) {
      User.authenticate({ user, pass }, gotUser);

      function gotUser(err, user) {
        if (err) {
          return callback(err);
        }
        callback(null, user);
      }
    })
  )
  .use(function (req, res) {
    res.end('I\'m a secert\n');
  });

app.listen(3000);
